import os, sys
import re

from vyperlogix.misc import _utils
from vyperlogix.misc.FormatWithCommas import FormatWithCommas

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

def main(top,file_endswith='.py'):
    loc = 0
    __reFilter = '[._]svn'
    rejecting_re=re.compile(__reFilter)
    for root, dirs, files in _utils.walk(top, topdown=True, rejecting_re=rejecting_re):
	_files = [_f for _f in files if (_f.endswith(file_endswith) if (isinstance(file_endswith,str)) else any([_f.endswith(ending) for ending in file_endswith]) if (isinstance(file_endswith,list)) else False)]
	for f in _files:
	    fname = os.sep.join([root,f])
	    if (os.path.exists(fname)):
		lines = _utils.readFileFrom(fname).split('\n')
		_loc = len(lines)
		print '%s has %d lines of code.' % (fname,_loc)
		loc += _loc
    print 'lines of code is "%s".' % (FormatWithCommas('%d',loc))
    return loc

def report_loc(dirs):
    _total_lines_of_code = 0
    reportIO = StringIO()
    for dirname in dirs:
	_loc = main(dirname,file_endswith=['.rb','.py'])
	_total_lines_of_code += _loc
	print >>reportIO, 'lines of code in "%s" is "%s".' % (dirname,FormatWithCommas('%d',_loc))
    print >>reportIO, 'total lines of code is "%s".' % (FormatWithCommas('%d',_total_lines_of_code))
    reportIO.flush()
    print reportIO.getvalue()

if (__name__ == '__main__'):
    #dir1 = r'Z:\@myMagma\!!python-trunk'
    #dir2 = r'Z:\@myMagma\python-local-new-trunk'
    #dir3 = r'Z:\@myMagma\python-local-new-trunk-ruby-daemon'
    #dir4 = r'Z:\@myMagma\python-local-projects'
    #dir5 = r'Z:\@myMagma\python-local-trunk'
    #dirs = [dir1,dir2,dir3,dir4,dir5]
    #report_loc(dirs)

    #dirp1 = r'Z:\python projects'
    #main(dirp1)

    #dirr1 = r'Z:\@myMagma\molten-trunk\molten3'
    #dirr2 = r'Z:\@myMagma\molten-trunk\molten4'
    #dirr3 = r'Z:\@myMagma\molten-trunk\molten5'
    #dirr4 = r'Z:\@myMagma\molten-trunk\molten_python'
    #dirr5 = r'Z:\@myMagma\molten-trunk\ruby-python-bridge'
    #dirs = [dirr1,dirr2,dirr3,dirr4,dirr5]
    #report_loc(dirs)

    #dirp2 = r"Z:\python projects\@lib\vyperlogix"
    #main(dirp2)

    #dirp2 = r"Z:\python projects\_django-projects\magma_molten_4.0.1"
    #main(dirp2) # 2089

    #dirp2 = r"Z:\python projects\_django-projects\magma_molten_4.1.0"
    #main(dirp2) # 2103
